import React from 'react'
import ReactDOM from 'react-dom'
import {HashRouter as Router, Route, Link, Switch} from 'react-router-dom'
import store from './store'

const App = () => {
    return (
        <Router>
        <div>
            <h1>APP</h1>
            <ul>
                <li><Link to="/a">A</Link></li>
                <li><Link to="/b">B</Link></li>
            </ul>
            <hr/>
            <Route path="/a" component={PageA}></Route>
            <Route path="/b" component={PageB}></Route>
        </div>
        </Router>
    )
}


class PageA extends React.Component{
    constructor() {
        super()
        this.state = {
            name: store.getState().name 
        }

        this.subscribe = store.subscribe(() => {//监听修改数据
            this.setState({
                name: store.getState().name
            })
        })
    }

    render() {
        return (
            <div>
                <h1>A</h1>
                <p>{this.state.name}</p>
            </div>
        )
    }

    componentWillUnmount() {
        this.subscribe()
    }
}

class PageB extends React.Component{
    render() {
        return (
            <div>
                <h1>B</h1>
                <button onClick={() => {
                    store.dispatch({
                        type: 'CHANGE_NAME'
                    })
                }}>点我修改A中数据</button>
            </div>
        )
    }
}

ReactDOM.render(<App/>, document.getElementById('root'))